﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel.Composition;

namespace Kindler.Processors
{
    [Export(typeof(IProcessor))]
    public class ChapterProcessor : IProcessor
    {
        public void Process(XDocument htmlBook)
        {
            // Need a namespace for the mbp prefix so just make up a kindle one
            var namespaceAttribute = new XAttribute(XNamespace.Xmlns + "mbp", 
                XNamespace.Get("http://www.amazon.com/kindle/html"));
            htmlBook.Root.Add(namespaceAttribute);

            XName elementName = XName.Get("{http://www.amazon.com/kindle/html}pagebreak");

            var headers = from XElement header in htmlBook.Descendants("h1")
                          select header;

            foreach (var header in headers)
            {
                // Add page breaks before each chapter
                header.AddBeforeSelf(new XElement(elementName));
                // Add some padding below the chapter title
                header.AddAfterSelf(new XElement("br"));
            }
        }
    }
}